import React, { useContext, memo } from 'react';
import { Form, Input, Checkbox, Button } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import './index.less';
import useRouter from 'hooks/use-router';
import { useLocalStorageState } from 'ahooks';

const LoginForm = () => {
    /** router 初始化 */
    const router = useRouter();

    /** 表单初始化 */
    const [form] = Form.useForm();
    const [storedName, setStoredName] = useLocalStorageState('userName', '');
    const [remember, setRemember] = useLocalStorageState('remember', false);
    form.setFieldsValue({ remember, userName: remember ? storedName : '' });

    /** 登录 */
    const login = async () => {
        await form.validateFields();
        const username = form.getFieldValue('userName');
        const password = form.getFieldValue('password');
        const remember = form.getFieldValue('remember');

        setStoredName(username);
        setRemember(remember);
        router.push('/home');
    };
    return (
        <Form form={form}>
            <Form.Item name="userName" rules={[{ required: true, message: '请输入用户名!' }]}>
                <Input placeholder="请输入用户名" prefix={<UserOutlined />} />
            </Form.Item>
            <Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
                <Input.Password placeholder="请输入密码" prefix={<LockOutlined />} onPressEnter={login} />
            </Form.Item>
            <Form.Item name="remember" valuePropName="checked">
                <Checkbox>记住用户名</Checkbox>
            </Form.Item>
            <Form.Item>
                <Button type="primary" danger onClick={login} block>
                    登录
                </Button>
            </Form.Item>
        </Form>
    );
};
export default memo(LoginForm);
